﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[DefaultExecutionOrder(-1)]
[ExecuteInEditMode]
[AddComponentMenu("UI/Behavior/FrameIndex")]
public class UIFrameIndex : MonoBehaviour,IUIIndex
{

    public Sprite[] sprites;
    public bool lockedSize = false;

    [Tooltip("改动的目标图标，不填写则自动获取默认值")]
    public Image targetImage;

    [SerializeField]
    private int _index;
    public int index
    {
        get
        {
            return _index;
        }
        set
        {
            if (value > sprites.Length - 1) value = sprites.Length - 1;
            if (value < 0) value = 0;
            UpdateFromIndex(value);
            _index = value;
        }
    }

#if UNITY_EDITOR
    bool _dirty = false;
    private void OnValidate()
    {
        if (sprites == null || sprites.Length <= 0) return;
        if (_index > sprites.Length - 1) _index = sprites.Length - 1;
        if (_index < 0) _index = 0;
        _dirty = true;
    }


    private void Update()
    {
        if (_dirty)
        {
            _dirty = false;
            UpdateFromIndex(_index);
        }
    }

#endif

    private Image GetImage()
    {
        if (this.targetImage == null)
        {
            this.targetImage = GetComponent<Image>();
        }
        return this.targetImage;
    }

    private void Awake()
    {
        this.GetImage();//开头获取一次
    }


    private void UpdateFromIndex(int value)
    {
        var image = this.GetImage();
        if (sprites[value])
        {
            image.sprite = sprites[value];
            if (!lockedSize) image.SetNativeSize();
        }
    }


}
